package com.coldlz.mmp.pojo;

import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;

import java.util.concurrent.Flow;
import java.util.concurrent.SubmissionPublisher;

public class TemplatePublisher<T> implements Publisher<T> {

    final SubmissionPublisher<T> publisher;

    public TemplatePublisher(SubmissionPublisher<T> publisher) {
        this.publisher = publisher;
    }

    public void submit(T item){
        publisher.submit(item);
    }

    @Override
    public void subscribe(Subscriber<? super T> subscriber) {
        publisher.subscribe(new Subscriber0<>(subscriber));
    }

    private static class TemplateSubscription implements Subscription {
        Flow.Subscription subscription;

        private TemplateSubscription(Flow.Subscription subscription) {
            this.subscription = subscription;
        }

        @Override
        public void request(long n) {
            subscription.request(n);
        }

        @Override
        public void cancel() {
            subscription.cancel();
        }
    }

    private static class Subscriber0<T> implements Flow.Subscriber<T> {
        Subscriber<? super T> subscriber;

        private Subscriber0(Subscriber<? super T> subscriber) {
            this.subscriber = subscriber;
        }

        @Override
        public void onSubscribe(Flow.Subscription subscription) {
            subscriber.onSubscribe(new TemplateSubscription(subscription));
        }

        @Override
        public void onNext(T item) {
            subscriber.onNext(item);
        }

        @Override
        public void onError(Throwable throwable) {
            subscriber.onError(throwable);
        }

        @Override
        public void onComplete() {
            subscriber.onComplete();
        }
    }
}
